<?php

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\api\model\Order as OrderModel;
use app\common\model\User as UserModel;
use think\Db;

/**
 * 个人中心主页
 * Class Index
 * @package app\api\controller\user
 */
class Index extends Controller
{
    private $user;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize() {
        parent::_initialize();
        $this->user = $this->getUser();
    }

    /**
     * 获取当前用户信息
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        // 订单总数
        $model = new OrderModel;
        $orderCount = [
            'payment' => $model->getCount($userInfo['user_id'], 'payment'),
            'received' => $model->getCount($userInfo['user_id'], 'received'),
        ];
        return $this->renderSuccess(compact('userInfo', 'orderCount'));
    }
    public function subscribe() {

        #--获取前端表单数据：

        $data['referee'] = $this->request->get()['b_id'];

        $model = new UserModel;#halt($data);

        #-- 开启事务
        Db::startTrans();
        try {
            #-- 修改user表：
            $res = $model->allowField(true)->save($data, ['user_id' => $this->user['user_id']]);
            Db::commit();
            return $this->renderSuccess($res);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError("出错了，请联系管理员！错误信息：".$e->getMessage());
        }

    }
}
